 	.syntax unified
 	.cpu cortex-m3
 	.thumb
 	.align 2
 	.global	asm_variance
 	.thumb_func
asm_variance:

 	STMFD R13!, {R4-R12}
 	@R11 is used as a temporary pointer
 	@R10 & R12 are used as a temporary var such as the loop index

 	@declare circular buffer, CBptr, CBcnt and load to register
 	.lcomm CB 24
 	.lcomm CBptr 4
 	.lcomm CBcnt 4
 	LDR R6, =CB
 	LDR R11, =CBptr
 	LDR R7, [R11,#0]
 	LDR R11, =CBcnt
 	LDR R8, [R11,#0]

	@update circular buffer
	@update CBcnt
	CMP R8,#6			@increase CBcnt by 1 if < 6
	IT LT
	ADDLT R8,R8,#1
	@update CBptr
	SUB R12,R7,R6
	CMP R12,#20
	ITE EQ
	MOVEQ R7,R6
	ADDNE R7,R7,#4

	@check whether flush the memory or not
 	CMP R2, #1
 	ITT EQ
	MOVEQ R8,#1
	MOVEQ R7,R6

	@update CB
	STR R0,[R7]

	@compute variance
	@clear R4 and R5
	MOV R4, #0 @sum of (xi-x)2
	MOV R5, #0 @used when compute (xi-x)2
	MOV R11, R6
	MOV R12,R8
	VAR_LOOP:
	LDR R5,[R11],#0x4
	SUB R5,R5,R1
	MUL R5,R5,R5
	ADD R4,R4,R5

	SUBS R12,R12,#1
	BGT VAR_LOOP
	SDIV R0,R4,R8

	@compute maaaaaaaaax
	@R11 is the current pointer
	@R12 is the LOOP counter
	MOV R11,R6
	MOV R12,R8
	@R9 is the max value
	@R10 is the current process value
	LDR R9,[R11,#0]
	MAX_LOOP:
	LDR R10,[R11],#4
	CMP R9,R10
	IT LT
	MOVLT R9,R10

	SUBS R12,R12,#1
	BGT MAX_LOOP
	STR R9,[R3]

	LDR R11, =CBptr
 	STR R7, [R11]
 	LDR R11, =CBcnt
 	STR R8, [R11]

	LDMFD R13!, {R4-R12}
 	BX  LR
